/// <reference path="../helpers.ts" />

module $Xrm.Messages {
    export class ErrorResponse {
        public ResponseXml: Document;
        public ResponseText: string;

        public Error: string;

        constructor(responseXml: Document, responseText: string) {
            this.ResponseXml = responseXml;
            this.ResponseText = responseText;
            this.Error = "";

            this.ParseError();
        }

        private ParseError() {
            if (this.ResponseXml.firstChild != null && this.ResponseXml.firstChild.firstChild) {
                // todo: check that s:Fault is the right node and faultstring is the correct node, seen variations of this...
                var fault = _xml.getChildNode(this.ResponseXml.firstChild.firstChild, "s:Fault");
                if (fault != null && fault != undefined) {
                    var faultTextNode = _xml.getChildNode(fault, "faultstring");
                    if (faultTextNode != null && faultTextNode != undefined) {
                        this.Error = _xml.getText(faultTextNode);
                    }

                    var detail = _xml.getChildNode(fault, "detail");
                    if (detail != null && detail != undefined) {
                        var osf = _xml.getChildNode(detail, "OrganizationServiceFault");
                        if (osf != null && osf != undefined) {
                            this.Error += _string.format("\r\nOrganizationServiceFault.Message: {0}",
                                _xml.getText(_xml.getChildNode(osf, "Message")));

                            var inner = _xml.getChildNode(osf, "InnerFault");
                            if (inner != null && inner != undefined) {
                                this.Error += _string.format("\r\nOrganizationServiceFault.InnerFault.Message: {0}",
                                    _xml.getText(_xml.getChildNode(osf, "Message")));
                            }
                        }
                    }
                }
            }
            else {
                this.Error = this.ResponseText;
            }
        }
    }
}